package com.ailot.cloud.auth.handler;

import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.security.authentication.model.JwtUser;
import com.ailot.cloud.base.security.utils.JWTUtil;
import com.ailot.cloud.base.security.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从authentication中获取用户信息
        final JwtUser userDetail = (JwtUser) authentication.getPrincipal();
        log.info("{}:登录成功", userDetail.getUsername());
        String token = JWTUtil.createToken(userDetail);
        Result result = Result.success("登录成功", token);
        ResponseUtil.response(response, result);
    }
}
